package light.head.controller.oa;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.ApplyInfoDAO;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.ApplyInfo;
import light.head.model.ApplyItem;
import light.head.model.AuditStatus;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 申请单管理（物品申请审核菜单）
 * @author yy
 */
@Controller
@RequestMapping(value = Url.APPLY_MANAGER)
public class ApplyManagerController extends SupporterController {
	
	private ApplyInfoDAO applyDAO;
	private OrganDAO organDAO;
	private AuditStatusDAO asDAO;
	private UserInfoDAO userDAO;
	private MessageTemplateDAO mtDAO;
	private MessageDAO msgDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.APPLY_MANAGER_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED, Parm.TIME1, Parm.TITLE, Parm.TIME2, Parm.EXAMIN);
		
		// 获取根机构配置的物品申请流程节点
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (applyDAO.findByMap_1(organDAO.getSonCodeList(oc), cu_roleCode(request), map, pb) == RESULT.SUCCESS) {
			// 讲对应的审核状态放到对应的
			ApplyInfo applyInfo = null;
			for (Object o : pb.getResultList()) {
				applyInfo = (ApplyInfo) o;
				applyInfo.setAuditStatusList(asDAO.findByBusinessMcRc(Sys.B_ONE, applyInfo.getCode(), cu_roleCode(request)));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.APPLY_MANAGER_LIST);
	}

	// 单个申请单详情
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			ApplyInfo a = applyDAO.get(code);
			if (null != a) {
				a.setAuditStatusList(asDAO.findByBusinessMcRc(Sys.B_ONE, a.getCode(), cu_roleCode(request)));
				List<ApplyItem> list = applyDAO.findApplyItem(code);
				a.setAdList(list);
				request.setAttribute(Parm.APPLY, a);
			}
		}
		return new ModelAndView(Url.APPLY_MANAGER_DETAIL);
	}

	
	@RequestMapping(Url.UPDATEDESIGNATE_1)
	public void updateDesignate1(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		
		// 查询当前申请信息是否已被当前用户审核
		List<AuditStatus> asList = asDAO.findByRcMcAuBusiness(cu_roleCode(request), Integer.parseInt(code), cu_code(request), Sys.B_ONE);
		if (asList != null && asList.size() > 0 ) {
			print(response, Msg.EXISTS);
			return;
		}
		
		// 1.判断是否有审核权限 查询流程配置表
		List<AuditStatus> auList = asDAO.findByRcMcBusiness(cu_roleCode(request), Integer.parseInt(code), Sys.B_ONE);
		if (auList == null || auList.size() < 0) {
			print(response, Msg.ERROR);
			return;
		}
		
		// 判断是否有上一级审核
		//Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		Integer ishave = asDAO.ishave(cu_roleCode(request), Integer.parseInt(code), Sys.B_ONE, organDAO.getSonCodeList(cu_organCode(request)));
		if (ishave !=null && ishave > 1) {
			// 2.判断上一级审核节点是否已经审核通过，查询流程配置表和审核状态表
			Byte beforeStatus = asDAO.checkBeforeByBusinessRc(Sys.B_ONE, cu_roleCode(request), organDAO.getSonCodeList(cu_organCode(request)), Integer.parseInt(code));
			// 3.有审核权限，且上一级审核节点已经审核通过，进行保存本次审核状态
			if (beforeStatus == null || beforeStatus != Sys.B_ONE) {
				print(response, Msg.PARAMETER_ERROR);
				return;
			}
		}
		
		if (null != code) {
			List<AuditStatus> asList1 = asDAO.findAuditStatusBusiness(Integer.parseInt(code), cu_roleCode(request), Sys.B_ONE);
			for (AuditStatus as : asList1) {
				as.setStatus(Sys.B_ONE);
				as.setAu(cu_code(request));
				as.setAt(new Date());
				result = asDAO.upd(as);
				// 查询是否有下一节点，有就修改下一节点审核状态为当前审核状态并发送消息通知下一审核人，没有就通知申请提交人
				List<AuditStatus> pcList = asDAO.findByOcPcMcBusiness(as.getPc() + 1, Integer.parseInt(code), Sys.B_ONE);
				if (null != pcList && pcList.size() > 0) {
					for(AuditStatus aud : pcList){
						aud.setBeforeStatus(Sys.B_ONE);
						result = asDAO.upd(aud);
						Integer rc1 = userDAO.findByOc(aud.getCu(), aud.getOc());
						if (null != rc1 && rc1 == aud.getRc()){
							aud.setStatus(Sys.B_ONE);
							aud.setAt(new Date());
							aud.setAu(cu_code(request));
							List<AuditStatus> pc1List = asDAO.findByOcPcMcBusiness(aud.getPc() + 1, Integer.parseInt(code), Sys.B_ONE);
							if (null != pcList && pcList.size() > 0) {
								for(AuditStatus ad : pc1List){
									ad.setBeforeStatus(Sys.B_ONE);
									result = asDAO.upd(ad);
								}
								 //消息通知审核人
								String name =userDAO.findCode(aud.getAu());
								Integer rc = asDAO.findByMcOcPc(cu_organCode(request), aud.getMc(), aud.getPc() + 1);	// 获取该机构具有审核申请信息的角色编号
								if(null == rc ){
									print(response, Msg.ERROR);
									return;
								}
								List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
								List<Integer> rucs = new ArrayList<Integer>();
								for (UserInfo u : userList) {
									rucs.add(u.getCode());
								}
								ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
								List<ApplyItem> item = applyDAO.findApplyItem(Integer.parseInt(code));
								apply.setAdList(item);
								String content = mtDAO.applyFirstToTwo(apply, apply.getAn(), cu_realName(request), aud.getAt());
								msgDAO.sendToUsers("【" + name + "】提交申请单待审核通知", content, cu_code(request), cu_organCode(request), rucs);
								print(response,Msg.SUCCESS);
							} else {
								ApplyInfo re = applyDAO.get(Integer.parseInt(code));
								List<ApplyItem> item = applyDAO.findApplyItem(Integer.parseInt(code));
								re.setAdList(item);
								String content = mtDAO.throughToCu(re.getAt(), as.getAt());
								msgDAO.sendToUsers("【" + cu_realName(request) + "】审核通知", content, cu_code(request), cu_organCode(request), re.getAu());
								print(response,Msg.SUCCESS);
							}
						} else {
							 //消息通知审核人
							Integer rc = asDAO.findByMcOcPc(cu_organCode(request), as.getMc(), as.getPc() + 1);	// 获取该机构具有审核申请信息的角色编号
							if(null == rc ){
								print(response, Msg.ERROR);
								return;
							}
							List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
							List<Integer> rucs = new ArrayList<Integer>();
							for (UserInfo u : userList) {
								rucs.add(u.getCode());
							}
							ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
							List<ApplyItem> item = applyDAO.findApplyItem(Integer.parseInt(code));
							apply.setAdList(item);
							String content = mtDAO.applyFirstToTwo(apply, apply.getAn(), cu_realName(request), as.getAt());
							msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请单待审核通知", content, cu_code(request), cu_organCode(request), rucs);
							print(response,Msg.SUCCESS);
						}
						aud.setBeforeStatus(Sys.B_ONE);
						result = asDAO.upd(aud);
					}
				} else if (RESULT.SUCCESS == result) {
					ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
					List<ApplyItem> item = applyDAO.findApplyItem(Integer.parseInt(code));
					apply.setAdList(item);
					String content = mtDAO.throughToCu(apply.getAt(), as.getAt());
					msgDAO.sendToUsers("【" + cu_realName(request) + "】审核通知", content, cu_code(request), cu_organCode(request), apply.getAu());
					print(response,Msg.SUCCESS);
				}
			}
		}
	}
	
	@RequestMapping(Url.UPDATEDESIGNATE_2)
	public void updateDesignate2(String code, String remark,HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 查询当前申请信息是否已被当前用户审核
		List<AuditStatus> asList =  asDAO.findByRcMcAuBusiness(cu_roleCode(request), Integer.parseInt(code), cu_code(request),Sys.B_ONE);
		if (asList == null || asList.size() > 0) {
			print(response, Msg.EXISTS);
			return;
		}
		// 1.判断是否有审核权限 查询流程配置表
		List<AuditStatus> auList = asDAO.findByRcMcBusiness(cu_roleCode(request), Integer.parseInt(code), Sys.B_ONE);
		if (auList == null || auList.size() < 0) {
			print(response, Msg.ERROR);
			return;
		}
		// 判断是否有上一级审核
		//Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		Integer ishave = asDAO.ishave(cu_roleCode(request), Integer.parseInt(code), Sys.B_ONE, organDAO.getSonCodeList(cu_organCode(request)));
		if (ishave !=null && ishave > 1) {
			// 2.判断上一级审核节点是否已经审核通过，查询流程配置表和审核状态表
			Byte status = asDAO.checkBeforeByBusinessRc(Sys.B_ONE, cu_roleCode(request), organDAO.getSonCodeList(cu_organCode(request)), Integer.parseInt(code));
			// 3.有审核权限，且上一级审核节点已经审核通过，进行保存本次审核状态
			if (status == null || status != Sys.B_ONE) {
				print(response, Msg.PARAMETER_ERROR);
				return;
			}
		}
		
		if (null != code) {
			List<AuditStatus> asList1 = asDAO.findAuditStatusBusiness(Integer.parseInt(code), cu_roleCode(request),Sys.B_ONE);
			for (AuditStatus as : asList1) {
				as.setStatus(Sys.B_TWO);
				as.setAu(cu_code(request));
				as.setAt(new Date());
				as.setRemark(remark);
				if (RESULT.SUCCESS == asDAO.upd(as)) {
					ApplyInfo apply = applyDAO.get(Integer.parseInt(code));
					List<ApplyItem> item = applyDAO.findApplyItem(Integer.parseInt(code));
					apply.setAdList(item);
					String content = mtDAO.rejectTofirst(apply, cu_realName(request),as.getAt(), as.getRemark());
					msgDAO.sendToUsers("【" + cu_realName(request) + "】驳回了申请单", content, cu_code(request), cu_organCode(request), apply.getAu());
					print(response,Msg.SUCCESS);
				}
			}
		}
	}
	
	@Autowired
	public void setApplyDAO(ApplyInfoDAO applyDAO) {
		this.applyDAO = applyDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setAsDAO(AuditStatusDAO asDAO) {
		this.asDAO = asDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	
}
